import json
from urllib.parse import urlencode, parse_qs
from urllib.request import urlopen

from rest_framework.response import Response

from mall.settings import QQ_APP_ID, QQ_REDIRECT_URL, QQ_APP_KEY


class QQAssistance(object):
    # 获取qq登陆授权url
    def get_auth_url(self, state):

        # base_url  注意在后面加 ？
        base_url = 'https://graph.qq.com/oauth2.0/authorize?'

        # 设置参数
        params = {
            'response_type': 'code',
            'client_id': QQ_APP_ID,
            'redirect_uri': QQ_REDIRECT_URL,
            'state': '/',
        }

        # urlencode()  把字典转换程查询字符串格式
        full_url = base_url + urlencode(params)

        return full_url

    # 获取token
    def get_token_by_code(self, code):
        # base_dir  ?
        base_dir = 'https://graph.qq.com/oauth2.0/token?'

        # 参数
        params = {
            'grant_type': 'authorization_code',
            'client_id': QQ_APP_ID,
            'client_secret': QQ_APP_KEY,
            'code': code,
            'redirect_uri': QQ_REDIRECT_URL,
        }

        # 拼接url urlencode
        full_url = base_dir + urlencode(params)

        # urlopen 访问qq服务器
        response = urlopen(full_url)
        data = response.read().decode()  # data 即为返回的access_taken

        # urllib.parse.parse_qs(qs) # 把查询字符串转换成字典
        query_params = parse_qs(data)  # 转换后的value是列表

        # 获取token
        access_token = query_params.get('access_token')[0]
        print('access_token',access_token)
        if access_token is None:
            raise Exception('获取token失败')

        return access_token

    # 获取openid
    def get_openid_by_token(self, access_token):
        base_dir = 'https://graph.qq.com/oauth2.0/me?'
        params = {
            'access_token': access_token
        }
        full_url = base_dir + urlencode(params)

        response = urlopen(full_url)
        data = response.read().decode()

        try:
            openid_dict = json.loads(data[10: -4])
        except Exception as e:
            raise Exception('获取用户数据错误')

        openid = openid_dict.get('openid')
        print(openid)

        return openid

